<?php
namespace app\index\controller;



use app\index\code\BaseCode;
use app\index\logic\UserLogic;
use app\index\model\LocationModel;
use app\index\model\UserLocationModel;
use app\index\model\UserModel;
use app\index\util\Response;
use think\Request;
use think\Session;

class Index extends Base
{
    public $user_info;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->user_info = UserLogic::user_info();
    }

    public function index(){
        $seed = md5(str_rand());
        Session::set('seed',$seed);
        $this->assign('seed',$seed);
        return view();
    }
    public function location(){
        $longitude = Request::instance()->param('longitude','0');
        $latitude = Request::instance()->param('latitude','0');
        $seed = Request::instance()->param('seed','htmlspecialchars');
        if($seed != Session::get('seed')){
            Response::json(BaseCode::FAIL,'请刷新页面后再试');
        }
        Session::delete('seed');
        $model = new UserLocationModel();
        $log_list = $model->where(['user_id'=>$this->user_info['user_id']])->order('add_time desc')->select();
        if($log_list){
//            if(count($log_list) == 10){
//                Response::json(BaseCode::FINISH,'您已完成所有的目标');
//            }
            if($log_list[0]['add_time'] + 6 * 30 > time()) {//还没到5分钟
                Response::json(BaseCode::FAIL,'距离上次打卡还不够5分钟，请稍后再试~');
            }
        }
        $model = new LocationModel();
        $list = $model->select();
        $user_location = new UserLocationModel();
        $have_location = false;
        $have_location_id = 0;
        foreach ($list as $value){
            $dis = $this->get_distance([$latitude,$longitude],[$value['latitude'],$value['longitude']]);
            if($dis < 250){
                $res = $user_location->where(['location_id'=>$value['id'],'user_id'=>$this->user_info['user_id']])->find();
                if($res){//已经打过卡的
                    $have_location = true;
                    $have_location_id = $value['id'];
                }else{
                    $data = [];
                    $data['user_id'] = $this->user_info['user_id'];
                    $data['longitude'] = $longitude;
                    $data['latitude'] = $latitude;
                    $data['location_id'] = $value['id'];
                    $data['distance'] = $dis;
                    $data['add_time'] = time();
                    $user_location->isUpdate(false)->save($data);
                    Response::json(BaseCode::SUCCESS,'您已成功获取'.$value['name'].'的印章，请继续努力',['id'=>$data['location_id']]);
                }
            }
        }
        if($have_location){
            Response::json(BaseCode::SUCCESS,'这里已打卡成功了，快看下一个地点是哪里',['id'=>$have_location_id]);
        }else{
            Response::json(BaseCode::FAIL,'打卡失败');
        }
    }
    public function log(){
        $model = new LocationModel();
        $list = $model->select();
        $model = new UserLocationModel();
        $log = $model->where(['user_id'=>$this->user_info['user_id']])->select();
        foreach ($list as $list_value){
            $data = [];
            $data['longitude'] = round($list_value['longitude'],6);
            $data['latitude'] = round($list_value['latitude'],6);
            $data['name'] = $list_value['name'];
            $data['is_log'] = 0;
            foreach ($log as $log_value){
                if($log_value['location_id'] == $list_value['id']){
                    $data['is_log'] = 1;
                    break;
                }
            }
            $this->assign('icon_'.$list_value['id'],$data);
        }
        if(count($log) >= 2 || $this->is_debug == true){
            $this->assign('can_exchange',1);
            $user_model = new UserModel();
            $info = $user_model->where(['id'=>$this->user_info['user_id']])->find();
            if(empty($info['mobile']) || empty($info['name'])){
                $this->assign('have_check_mobile',0);
            }else{
                $this->assign('have_check_mobile',1);
            }
            if($info['verify'] == 1){
                $this->assign('verify_time',$info['verify_time']);
                $this->assign('have_verify',1);
            }else{
                $this->assign('have_verify',0);
            }
        }else{
            $this->assign('have_check_mobile',0);
            $this->assign('can_exchange',0);
            $this->assign('have_verify',0);
        }
        return view();
    }
    public function exchange(){
        if($this->is_debug == false){
            $model = new UserLocationModel();
            $count = $model->where(['user_id'=>$this->user_info['user_id']])->count();
            if($count < 2){
                $this->error('打卡数量还没足够，请继续努力');
            }
        }
        $url = url('/index/index/verify',['user_id'=>$this->user_info['user_id']],true,true);
        $this->assign('qrcode',$url);
        return view();
    }
    public function check_mobile(){
        $user_id = $this->user_info['user_id'];
        $name = Request::instance()->param('name','');
        $mobile = Request::instance()->param('mobile','');
        if($name == ''){
            Response::json(BaseCode::FAIL,'姓名不能为空');
        }
        if($this->is_mobile($mobile) == false){
            Response::json(BaseCode::FAIL,'请输入正确的手机号码');
        }
        $model = new UserModel();
        $user = $model->where(['id'=>$user_id])->find();
        if($user == false){
            Response::json(BaseCode::FAIL,'用户不存在');
        }
        if($user['verify'] == 1){
            Response::json(BaseCode::FINISH,'您已兑换过');
        }
        if($this->is_debug == false){
            $log = new UserLocationModel();
            $count = $log->where(['user_id'=>$user_id])->count();
            if($count < 2){
                Response::json(BaseCode::FAIL,'兑换失败');
            }
        }
        $model->isUpdate(true)->save(['name'=>$name,'mobile'=>$mobile],['id'=>$user_id]);
        Response::json(BaseCode::SUCCESS,'兑换成功');



    }

    private  function is_mobile($data){
        $reg = '/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/';
        if(preg_match($reg,$data)){
            return true;
        }else{
            return false;
        }
    }

    public function verify(){
        $user_id = Request::instance()->param('user_id',0,'intval');
        $model = new UserModel();
        $user = $model->where(['id'=>$this->user_info['user_id']])->find();
        if($user['verify_auth'] == 0){
            $this->assign('success',0);
            $this->assign('msg','对不起你没有权利进行核销！');
            return view();
        }
        $info = $model->where(['id'=>$user_id])->find();
        if($info == false){
            $this->assign('success',0);
            $this->assign('msg','要核销的用户不存在');
            return view();
        }
        if($this->is_debug == false){
            $log = new UserLocationModel();
            $total = $log->where(['user_id'=>$user_id])->count();
            if($total < 2){
                $this->assign('success',0);
                $this->assign('msg','该用户打卡数量还不够2！');
                return view();
            }
        }

        if($info['verify'] == 1){
            $this->assign('success',0);
            $this->assign('msg','该用户已核销,核销时间为'.date('Y-m-d H:i:s',$info['verify_time']));
            return view();
        }else{
            $this->assign('success',1);
            $this->assign('msg','核销成功,用户已获得印章X'.$total.'个');
            $data = [];
            $data['verify'] = 1;
            $data['verify_time'] = time();
            $data['verify_user_id'] = $this->user_info['user_id'];
            $model->isUpdate(true)->save($data,['id'=>$user_id]);
            return view();
        }
    }













    /**
     * 根据起点坐标和终点坐标测距离
     * @param  [array]   $from 	[起点坐标(经纬度),例如:array(118.012951,36.810024)]
     * @param  [array]   $to 	[终点坐标(经纬度)]
     * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
     * @param  [int]     $decimal   精度 保留小数位数
     * @return [string]  距离数值
     */
    function get_distance($from,$to,$km=false,$decimal=2){
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6370.996; // 地球半径系数

        $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;

        if($km){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }
}
